package com.huang.core.util

import androidx.annotation.IntRange
import java.lang.Exception
import java.lang.StringBuilder
import java.text.DecimalFormat

object NumberUtil {
    fun string2Double(value: String, default: Double = 0.0): Double {
        return try {
            value.toDouble()
        } catch (e: Exception) {
            default
        }
    }

    fun string2Int(value: String, default: Int = 0): Int {
        return try {
            value.toInt()
        } catch (e: Exception) {
            default
        }
    }

    fun string2Long(value: String, default: Long = 0L): Long {
        return try {
            value.toLong()
        } catch (e: Exception) {
            default
        }
    }

    fun string2Float(value: String, default: Float = 0f): Float {
        return try {
            value.toFloat()
        } catch (e: Exception) {
            default
        }
    }

    fun string2Short(value: String, default: Short = 0): Short {
        return try {
            value.toShort()
        } catch (e: Exception) {
            default
        }
    }

    fun format(value: Double, @IntRange(from = 0, to = Int.MAX_VALUE.toLong()) decimal: Int): String {
        val formatStr = StringBuilder("#")
        if (decimal > 0) {
            formatStr.append(".")
            for (i in 1..decimal) formatStr.append("#")
        }
        return format(value, DecimalFormat(formatStr.toString()))
    }

    fun format(value: Double, format: DecimalFormat): String {
        return format.format(value)
    }

}